package cn.cerc.sample.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cn.cerc.db.core.Handle;
import cn.cerc.db.core.ISession;
import cn.cerc.mis.core.AbstractForm;
import cn.cerc.mis.core.Application;
import cn.cerc.mis.core.IErrorPage;
import cn.cerc.mis.core.IForm;
import cn.cerc.mis.core.IPage;
import cn.cerc.mis.other.PageNotFoundException;
import cn.cerc.sample.ui.UICustomPage;
import cn.cerc.ui.vcl.UIDiv;

@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
@Primary
public class AppErrorPage extends AbstractForm implements IErrorPage {

    @Override
    public String getErrorPage(HttpServletRequest req, HttpServletResponse resp, Throwable error) {
        try (ISession session = Application.getSession()) {
            session.setRequest(req);
            session.setResponse(resp);
            Handle handle = new Handle(session);
            IForm from = (IForm) Application.getBean(handle, "appErrorPage");
            UICustomPage jspPage = new UICustomPage(from);
            jspPage.addCssFile("css/style-pc-5.css");
            jspPage.addCssFile("css/summer.css");

            String msg = "";
            if (error != null)
                msg = error.toString().substring(error.toString().indexOf(":") + 1);

            String error_hint = "非常抱歉，您此项请求无法处理！";
            if (error instanceof PageNotFoundException)
                error_hint = "抱歉您请求的 Page 没有找到";

            UIDiv div = new UIDiv(jspPage.getContent());
            div.setText(String.format("%s,%s", msg, error_hint));

            return jspPage.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public IPage execute() {
        return null;
    }

    @Override
    public String getName() {
        return "错误页面";
    }

}
